package com.qufadai.mvc.util;

import java.util.HashMap;
import java.util.Map;

import com.qufadai.mvc.exception.NoneInstanceCreate;

/**
 * 负责生成相应的类的方法
 * 
 * @author Administrator
 * 
 */
public abstract class ClassUtil {
	@SuppressWarnings("unchecked")
	private static Map<String, Class> container = new HashMap<String, Class>();

	@SuppressWarnings("unchecked")
	public static Object findInstance(String name) {
		if (container.containsKey(name)) {
			return createInstance(container.get(name));
		}
		Class cla = findClass(name);
		container.put(name, cla);
		return createInstance(findClass(name));
	}

	@SuppressWarnings("unchecked")
	private static Class findClass(String name) {
		try {
			return Class.forName(name);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		throw new RuntimeException("Class not find with : " + name);
	}

	@SuppressWarnings("unchecked")
	private static Object createInstance(Class cla) {
		try {
			return cla.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		throw new NoneInstanceCreate();
	}

}
